package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.Map;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData>{
    //因为SubjectExcelListener不能交给spring容器管理，需要自己new，不能注入其他对象
    //所以不能实现数据库的操作
    public EduSubjectService SubjectService;
    public SubjectExcelListener() {

    }
    public SubjectExcelListener(EduSubjectService subjectService) {
        SubjectService = subjectService;
    }
  //一行一行的读取excel文件内容
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
  //判断文件是否为空
        if (subjectData==null){
            throw new GuliException(20001,"文件数据为空");
        }
        //文件一行一行的读取，每次读取都有两个值，第一个值为一级分类，第二个值为二级分类
        //添加一级分类
        EduSubject existOneSubject = this.existOneSubject(SubjectService, subjectData.getOneSubjectName());
        if (existOneSubject==null){//如果没有相同的一级分类，那就添加
           existOneSubject=new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());//添加一级分类的名称
            SubjectService.save(existOneSubject);

        }
        //获取一级分类的id值
        String pid=existOneSubject.getId();
        //添加二级分类
        EduSubject existTwoSubject = this.existTwoSubject(SubjectService, subjectData.getTwoSubjectName(),pid);
        if (existTwoSubject==null){//如果没有相同的一级分类，那就添加
            existTwoSubject=new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());//添加一级分类的名称
            SubjectService.save(existTwoSubject);

        }
    }
    //判断一级分类是否重复
    public EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",0);
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }
    //判断二级分类是否重复
    public EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }

    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
